import pandas as pd
from PyQt5.QtCore import pyqtSignal
from new_func.tools import Tool
from resources.average_value import Average_Form
from PyQt5.QtWidgets import QFrame


class AverageWidget(QFrame, Average_Form):
    error = pyqtSignal()

    def __init__(self, text, parent=None):
        super(AverageWidget, self).__init__(parent=parent)
        # self.unpack_ui = Average_Form()
        # self.unpack_ui.setupUi(self)
        self.setupUi(self)
        self.setObjectName(text.replace(' ', '-'))

        self.tool = Tool()
        self.currentSheet = None
        self.signals()

    def signals(self):
        """按钮触发， 主动调用"""
        self.average_filepath_btn.clicked.connect(lambda: self.tool.handle_path(self.average_filepath_line))
        self.average_filepath_line.textChanged.connect(self.suffix_info)

    def suffix_info(self):
        """检测后缀"""
        self.tool.get_suffix(self.average_filepath_line)
        if self.tool.suffix not in ['.csv', '.xlsx']:
            self.tool.show_error(self, "❗️文件错误", "文件后缀错误")
        self.read_file()

    def read_file(self):
        """读取csv以及excel，写入combox列"""
        if self.tool.path:
            self.header_box_clear()
            self.header_sheet_clear()
            if self.tool.suffix == ".csv":
                self.df = pd.read_csv(self.tool.path)
                self.average_sheet.addItems(list(self.df.columns))
            if self.tool.suffix == ".xlsx":
                self.df = pd.ExcelFile(self.tool.path)
                self.average_header_box.addItems(list(self.df.sheet_names))
                # header = list(pd.read_excel(self.df, sheet_name=list(self.df.sheet_names)[0]))  # 防止第一次加载没有值的情况
                self.load_sheet(list(self.df.sheet_names)[0])
                self.average_sheet.addItems(list(self.currentSheet.columns))
                self.average_header_box.currentTextChanged.connect(self.update_sheet_box)

    def header_box_clear(self):
        """检查并清除header_combox"""
        if self.average_header_box.count() > 0:
            self.average_header_box.clear()

    def header_sheet_clear(self):
        """检查并清楚sheet——combox的值"""
        if self.average_sheet.count() > 0:  # 如果有值，清除
            self.average_sheet.clear()

    def update_sheet_box(self):
        """如果前一个combox更新则继续更新当前combox"""
        self.header_sheet_clear()
        self.load_sheet(self.average_header_box.currentText())
        # header = list(pd.read_excel(self.df, sheet_name=self.average_header_box.currentText()).columns)
        self.average_sheet.addItems(list(self.currentSheet.columns))
        # self.average_sheet.addItems(header)

    def load_sheet(self, sheet_name):
        """加载指定表单"""
        self.currentSheet = pd.read_excel(self.df, sheet_name=sheet_name)

    def type_value(self, column):
        """判断类型"""
        # 修改类型判断机制
        if column.dtype in ['int64', 'float32']:
            # if column.dtype.kind in 'if':
            return str(round(column.mean(), 3))
        else:
            self.error.emit()


    def average_value(self):
        """计算列的平均值"""
        if self.tool.suffix == ".csv":
            current_text = self.average_sheet.currentText()
            self.average_value_line.setText(self.type_value(self.df[current_text][1]))
        if self.tool.suffix == ".xlsx":
            sheet_column = self.average_sheet.currentText()
            # 获取指定列所对应的值
            self.average_value_line.setText(self.type_value(self.currentSheet[sheet_column][1]))
